import { Request, Response } from 'express';
import { AuthRequest } from '../types';
import Work from '../models/Work';
import Team from '../models/Team';

// 【必须有 EXPORT】
export const getWorks = async (req: Request, res: Response) => {
    try {
        const works = await Work.find({ status: 'approved' })
            .sort({ createdAt: -1 })
            .populate('team', 'name');
        res.json(works);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
};

// 【必须有 EXPORT】
export const getWorkById = async (req: Request, res: Response) => {
    try {
        const work = await Work.findById(req.params.id).populate('team', 'name description');
        if (work) {
            res.json(work);
        } else {
            res.status(404).json({ message: 'Work not found' });
        }
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
};

// 【必须有 EXPORT】
export const createWork = async (req: AuthRequest, res: Response) => {
    const { title, description, thumbnailUrl, downloadUrl, githubUrl, tags, teamId } = req.body;
    const currentUser = req.user;
    try {
        if (!title || !description || !teamId) {
            return res.status(400).json({ message: 'Title, description, and teamId are required' });
        }
        if (!currentUser) {
            return res.status(401).json({ message: 'Not authorized' });
        }
        const team = await Team.findById(teamId);
        if (!team) {
            return res.status(404).json({ message: 'Team not found' });
        }
        const isMember = team.members.some((memberId: any) => memberId.equals(currentUser._id));
        if (!isMember) {
            return res.status(403).json({ message: 'Forbidden: You are not a member of this team' });
        }
        const work = new Work({
            title,
            description,
            thumbnailUrl,
            downloadUrl,
            githubUrl,
            tags,
            team: teamId,
        });
        const createdWork = await work.save();
        res.status(201).json(createdWork);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server Error' });
    }
};

// 【必须有 EXPORT】
export const updateWork = async (req: AuthRequest, res: Response) => {
    res.status(501).json({ message: 'Function not implemented' });
};

// 【必须有 EXPORT】
export const deleteWork = async (req: AuthRequest, res: Response) => {
    res.status(501).json({ message: 'Function not implemented' });
};

// 【必须有 EXPORT】
export const approveWork = async (req: AuthRequest, res: Response) => {
    res.status(501).json({ message: 'Function not implemented' });
};